<?php
// +----------------------------------------------------------------------
// | B5LaravelCMF V2.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare(strict_types=1);

namespace App\Extends\Services\Resume;

use App\Extends\Helpers\Functions;
use App\Models\Resume\PersonalResume;
use App\Models\System\Admin;
use App\Models\System\Struct;
use Elasticsearch\Client;
use Elasticsearch\ClientBuilder;
use Illuminate\Support\Facades\DB;

class ElasticService
{
    private $indexName = 'resume';

    protected function getClient(): Client
    {
        $hosts = [
            'elasticsearch:9200',         // IP + Port
            'elasticsearch',              // Just IP
            'elasticsearch:9200', // Domain + Port
            'elasticsearch',     // Just Domain
            'http://elasticsearch',        // SSL to localhost
            'https://elasticsearch:9200'  // SSL to IP + Port
        ];
        $client = ClientBuilder::create()->setHosts($hosts)->build();
        return $client;
    }

    /**
     * 搜索
     * @return array
     */
    public function search($keyword): array
    {
        $client = $this->getClient();
        $params = [
            'index' => $this->indexName,   //['my_index1', 'my_index2'],可以通过这种形式进行跨库查询
            'type' => 'normal_type',//['my_type1', 'my_type2'],
            'body' => [
                "highlight" => [
                    "pre_tags" => ["<fannao>"],
                    "post_tags" => ["</fannao>"],
                    "fields" => [
                        "skill_tag" => new \stdClass(),
                        "skill" => new \stdClass(),
                        "experience" => new \stdClass()
                    ]
                ],

//                "query" => [
//                    "bool" => [
//                        "should" => [
//                            ["match" => ["skill_tag" => $keyword]],
//                            ["match" => ["skill" => $keyword]],
//                            ["match" => ["experience" => $keyword]],
//                        ]
//                    ]
//                ],

                'from' => '0',  // 分页
                'size' => '200',  // 每页数量
//                'sort' => [  // 排序
//                    'age' => 'desc'   //对age字段进行降序排序
//                ]
            ]
        ];

        if ($keyword) {
            $params['body']['query'] = [
                "bool" => [
                    "should" => [
                        ["match" => ["skill_tag" => "($keyword)"]],
//                        ["match" => ["skill" => $keyword]],
//                        ["match" => ["experience" => $keyword]],
                    ]
                ]
            ];
        }
        $res = $client->search($params);
        return $res;
    }

    /**
     * 初始化索引
     * @return void
     */
    public function initElastic()
    {

        // 查询数据库-建索引
        $list = DB::table(PersonalResume::tableName())->select(["*"])->get();

        // Instantiate a new ClientBuilder  // Set the hosts
        $client = $this->getClient();

        $params = [
            'index' => $this->indexName,
            'client' => ['ignore' => 404]
        ];

        $client->indices()->delete($params);

//        $result = $client->indices()->getMapping($params);
//        if(array_key_exists('error', $result)) {
        $this->createElastic();
//        }
        // 清除所有数据重新输入
        foreach ($list as $value) {
            $params['body'][] = [
                'index' => [
                    '_index' => $this->indexName,
                    '_type' => 'normal_type',
                    '_id' => $value->id
                ]
            ];
            $params['body'][] = [
                'id' => $value->id,
                'username' => $value->username,
                'skill_tag' => $value->skill_tag,
                'skill' => $value->skill,
                'experience' => $value->experience,
                'username' => $value->username,
                'sex' => $value->sex
            ];
        }
        $client->bulk($params);

        echo "重建成功";

    }

    public function createElastic()
    {
        $client = $this->getClient();

        $params = [
            'index' => $this->indexName,  //索引名（相当于mysql的数据库）
            'body' => [
                'settings' => [
                    'index' => [
                        "analysis.analyzer.default.type" => "ik_smart" // 最粗粒度 ik_smart 最细粒度 ik_max_word
                    ]
                ],
                'mappings' => [
                    'normal_type' => [ //类型名（相当于mysql的表）
                        '_all' => [   //  是否开启所有字段的检索
                            'enabled' => 'false'
                        ],
                        'properties' => [ //文档类型设置（相当于mysql的数据类型）
                            'id' => [
                                'type' => 'integer' // 字段类型为整型
                            ],
                            'skill_tag' => [
                                'type' => 'text' // 字段类型为关键字,如果需要全文检索,则修改为text,注意keyword字段为整体查询,不能作为模糊搜索
                            ],

                            'skill' => [
                                'type' => 'text'
                            ],
                            'experience' => [
                                'type' => 'text'
                            ],
                            'sex' => [
                                'type' => 'integer'
                            ],
                            'username' => [
                                'type' => 'keyword'
                            ],
                        ]
                    ]
                ]
            ]
        ];
        $client->indices()->create($params);
    }
}
